﻿using AutoMapper;
using Common;
using Common.Dtos;
using IdentityModel;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using Sigma.Admin.API.Context.Entity;
using Sigma.Admin.API.Context.UnitOfWork;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace Sigma.Admin.API.Services
{
    public class LoginService : ILoginService
    {
        private readonly IUnitOfWork _work;
        private readonly IMapper _mapper;

        public LoginService(IUnitOfWork work, IMapper mapper)
        {
            _work = work;
            _mapper = mapper;
        }

        public async Task<ApiResponse> Login(LoginUserDto user)
        {
            try
            {
                //Password = Password.GetMD5();

                var model = await _work.GetRepository<UserEntity>().GetFirstOrDefaultAsync(predicate:
                    x => (x.Account.Equals(user.Account))&& x.PassWord.Equals(user.PassWord));
                if (model == null)
                    return new ApiResponse("账号或密码错误,请重试！");
               var keysid = JsonConvert.DeserializeObject<List<int>>(model.PermissionKey??"");
                var keys =new List<string>();
                if (!(keysid is null) && keysid.Count() != 0)
                {
                    keys.AddRange(_work.GetRepository<PermissionEntity>().GetAll(predicate:
                    x => keysid.Contains(x.Id)).Select(x=>x.PermissionKey).ToList());
                }
               var token = CreateJwtToken(keys);
                return new ApiResponse("登陆成功！",true, new UsersDto()
                {
                    Account = model.Account,
                    UserName = model.UserName,
                    Id = model.Id,
                    Token = token
                });
            }
            catch (Exception ex)
            {
                return new ApiResponse("登录失败！",false);
            }
        }

        /// <summary>
        /// 颁发token
        /// </summary>
        /// <returns></returns>

        private string CreateJwtToken(List<string> pkeyName)
        {
            var pkey = (pkeyName == null || pkeyName.Count() == 0) ? "" : JsonConvert.SerializeObject(pkeyName);

            var tokenDescriptor = new SecurityTokenDescriptor
            {

                Subject = new ClaimsIdentity(new List<Claim>
                {
                    new Claim(JwtClaimTypes.Id,Guid.NewGuid().ToString()),//要想实现注销令牌，后续要存进缓存
                    new Claim("pkey",pkey),
                }),
                Issuer = "Auth-",
                Audience = "WPF-client",
                // 过期时间，暂时30min
                Expires = DateTime.UtcNow.AddMinutes(30),
                SigningCredentials = new SigningCredentials(
                new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Sigma.Admin JsonWebToken WebApi")),//校验token的密钥，要和program配置的一样
                SecurityAlgorithms.HmacSha256Signature),
            };

            var handler = new JwtSecurityTokenHandler();
            var securityToken = handler.CreateJwtSecurityToken(tokenDescriptor);
            var token = handler.WriteToken(securityToken);
            return token;
        }



    }
}